package net.zigin.nhi.waste.net;

import android.content.Context;
import android.text.TextUtils;

import net.zigin.nhi.waste.constants.Constants;

import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.BuildConfig;
import me.goldze.mvvmhabit.http.cookie.CookieJarImpl;
import me.goldze.mvvmhabit.http.cookie.store.PersistentCookieStore;
import me.goldze.mvvmhabit.http.interceptor.logging.Level;
import me.goldze.mvvmhabit.http.interceptor.logging.LoggingInterceptor;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.Utils;
import okhttp3.Cache;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.internal.platform.Platform;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.fastjson.FastJsonConverterFactory;

public class HttpRetrofitClient {
    //超时时间
    private static final int DEFAULT_TIMEOUT = 2 * 60;
    //缓存时间
    private static final int CACHE_TIMEOUT = 10 * 1024 * 1024;

    private static String baseUrl;

    private static Context mContext = Utils.getContext();
    private static OkHttpClient okHttpClient;
    private static Retrofit retrofit;

    private Cache cache = null;
    private File httpCacheDirectory;
    private TokenInterceptor tokenInterceptor;

    public static void setBaseUrl(String baseUrl) {
        HttpRetrofitClient.baseUrl = baseUrl;
    }

    private static class SingletonHolder {
        private static HttpRetrofitClient INSTANCE = new HttpRetrofitClient();
    }

    public static HttpRetrofitClient getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public static HttpRetrofitClient getInstance(String url) {

        return new HttpRetrofitClient(url);
    }

    public static HttpRetrofitClient getInstance(String url, Map<String, String> urlParam) {
        return new HttpRetrofitClient(url, null, urlParam);
    }


    private HttpRetrofitClient() {
        this(baseUrl, null, null);
    }

    private HttpRetrofitClient(String url) {
        this(url, null, null);
    }

    private HttpRetrofitClient(String url, Map<String, String> headers, Map<String, String> urlParam) {

        if (TextUtils.isEmpty(url)) {
            url = Constants.baseUrl;
        }

        if (httpCacheDirectory == null) {
            httpCacheDirectory = new File(mContext.getCacheDir(), "http_cache");
        }

        try {
            if (cache == null) {
                cache = new Cache(httpCacheDirectory, CACHE_TIMEOUT);
            }
        } catch (Exception e) {
            KLog.e("Could not create http cache", e);
        }
        tokenInterceptor = new TokenInterceptor();
        if (headers != null) {
            tokenInterceptor.getHeaders().putAll(headers);
        }
        if (urlParam != null) {
            tokenInterceptor.getUrlParams().putAll(urlParam);
        }
        LoggingInterceptor mLoggingInterceptor = new LoggingInterceptor
                .Builder()//构建者模式
                .loggable(true) //是否开启日志打印
                .setLevel(Level.BODY) //打印的等级
                .log(Platform.INFO) // 打印类型
                .request("Request") // request的Tag
                .response("Response")// Response的Tag
                .addHeader("version", BuildConfig.VERSION_NAME)//打印版本
                .build();


        okHttpClient = new OkHttpClient.Builder()
                .cookieJar(new CookieJarImpl(new PersistentCookieStore(mContext)))
//                .cache(cache)
                .addInterceptor(tokenInterceptor)
//                .addInterceptor(new CacheInterceptor(mContext))
                .addInterceptor(mLoggingInterceptor)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
                // 这里你可以根据自己的机型设置同时连接的个数和时间，我这里8个，和每个保持时间为10s
                .build();
        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(url)
                .build();

    }

    public TokenInterceptor getTokenInterceptor() {
        return tokenInterceptor;
    }

    /**
     * create you ApiService
     * Create an implementation of the API endpoints defined by the {@code service} interface.
     */
    public <T> T create(final Class<T> service) {
        if (service == null) {
            throw new RuntimeException("Api service is null!");
        }
        return retrofit.create(service);
    }

    /**
     * /**
     * execute your customer API
     * For example:
     * MyApiService service =
     * HttpRetrofitClient.getInstance(MainActivity.this).create(MyApiService.class);
     * <p>
     * HttpRetrofitClient.getInstance(MainActivity.this)
     * .execute(service.lgon("name", "password"), subscriber)
     * * @param subscriber
     *
     * @param observable
     * @param subscriber
     */

    public static <T> T execute(Observable<T> observable, Observer subscriber) {
        observable.subscribeOn(Schedulers.io())//在当前线程执行subscribe()方法
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())//在UI线程执行观察者的方法
                .subscribe(subscriber);

        return null;
    }

}